<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java线程池,无界队列,饱和策略" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="1.概述好的软件设计不建议手动创建和销毁线程。线程的创建和销毁是非常耗 CPU 和内存的，因为这需要 JVM 和操作系统的参与。64位 JVM 默认线程栈是大小1 MB。这就是为什么说在请求频繁时为每个小的请求创建线程是一种资源的浪费。线程池可以根据创建时选择的策略自动处理线程的生命周期。重点在于：在资源（如内存、CPU）充足的情况下，线程池没有明显的优势，否则没有线程池将导致服务器奔溃。有很多的">
<meta name="keywords" content="java线程池,无界队列,饱和策略">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程池详解">
<meta property="og:url" content="http://www.zhizus.com/2016-09-02-current-threadpool.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="1.概述好的软件设计不建议手动创建和销毁线程。线程的创建和销毁是非常耗 CPU 和内存的，因为这需要 JVM 和操作系统的参与。64位 JVM 默认线程栈是大小1 MB。这就是为什么说在请求频繁时为每个小的请求创建线程是一种资源的浪费。线程池可以根据创建时选择的策略自动处理线程的生命周期。重点在于：在资源（如内存、CPU）充足的情况下，线程池没有明显的优势，否则没有线程池将导致服务器奔溃。有很多的">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://www.zhizus.com/images/threadPoolFramworkNew.png">
<meta property="og:image" content="http://www.zhizus.com/images/threadPoolFlow.jpg">
<meta property="og:updated_time" content="2018-08-02T01:02:29.235Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java线程池详解">
<meta name="twitter:description" content="1.概述好的软件设计不建议手动创建和销毁线程。线程的创建和销毁是非常耗 CPU 和内存的，因为这需要 JVM 和操作系统的参与。64位 JVM 默认线程栈是大小1 MB。这就是为什么说在请求频繁时为每个小的请求创建线程是一种资源的浪费。线程池可以根据创建时选择的策略自动处理线程的生命周期。重点在于：在资源（如内存、CPU）充足的情况下，线程池没有明显的优势，否则没有线程池将导致服务器奔溃。有很多的">
<meta name="twitter:image" content="http://www.zhizus.com/images/threadPoolFramworkNew.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2016-09-02-current-threadpool.html"/>





  <title> Java线程池详解 | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2016-09-02-current-threadpool.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Java线程池详解
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2016-09-02-current-threadpool.html" class="leancloud_visitors" data-flag-title="Java线程池详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="1-概述"><a href="#1-概述" class="headerlink" title="1.概述"></a>1.概述</h2><div class="note "><p>好的软件设计不建议手动创建和销毁线程。线程的创建和销毁是非常耗 CPU 和内存的，因为这需要 JVM 和操作系统的参与。64位 JVM 默认线程栈是大小1 MB。这就是为什么说在请求频繁时为每个小的请求创建线程是一种资源的浪费。线程池可以根据创建时选择的策略自动处理线程的生命周期。重点在于：在资源（如内存、CPU）充足的情况下，线程池没有明显的优势，否则没有线程池将导致服务器奔溃。有很多的理由可以解释为什么没有更多的资源。例如，在拒绝服务（denial-of-service）攻击时会引起的许多线程并行执行，从而导致线程饥饿（thread starvation）。除此之外，手动执行线程时，可能会因为异常导致线程死亡，程序员必须记得处理这种异常情况。</p>
</div>
<p>即使在你的应用中没有显式地使用线程池，但是像 Tomcat、Undertow这样的web服务器，都大量使用了线程池。所以了解线程池是如何工作的，怎样调整，对系统性能优化非常有帮助。
<a id="more"></a></p>
<h2 id="2-线程池的基础知识"><a href="#2-线程池的基础知识" class="headerlink" title="2.线程池的基础知识"></a>2.线程池的基础知识</h2><h3 id="2-1线程池的构造方法"><a href="#2-1线程池的构造方法" class="headerlink" title="2.1线程池的构造方法"></a>2.1线程池的构造方法</h3><p>Java提供了Executor框架提供了一套完善的多线程编程api，包括对线程生命周期，统计信息，程序管理机制，性能监控等功能。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadPoolExecutor</span> <span class="keyword">extends</span> <span class="title">AbstractExecutorService</span> </span>&#123;</span><br><span class="line">    .....</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,<span class="keyword">int</span> maximumPoolSize,<span class="keyword">long</span> keepAliveTime,TimeUnit unit,BlockingQueue&lt;Runnable&gt; workQueue)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,<span class="keyword">int</span> maximumPoolSize,<span class="keyword">long</span> keepAliveTime,TimeUnit unit,BlockingQueue&lt;Runnable&gt; workQueue,ThreadFactory threadFactory)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,<span class="keyword">int</span> maximumPoolSize,<span class="keyword">long</span> keepAliveTime,TimeUnit unit,BlockingQueue&lt;Runnable&gt; workQueue,RejectedExecutionHandler handler)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ThreadPoolExecutor</span><span class="params">(<span class="keyword">int</span> corePoolSize,<span class="keyword">int</span> maximumPoolSize,<span class="keyword">long</span> keepAliveTime,TimeUnit unit, BlockingQueue&lt;Runnable&gt; workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)</span></span>;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><p><code>corePoolSize</code>：核心池的大小，这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后，默认情况下，线程池中并没有任何线程，而是等待有任务到来才创建线程去执行任务，除非调用了prestartAllCoreThreads()或者<code>prestartCoreThread</code>()方法，从这2个方法的名字就可以看出，是预创建线程的意思，即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下，在创建了线程池后，线程池中的线程数为0，当有任务来之后，就会创建一个线程去执行任务，当线程池中的线程数目达到corePoolSize后，就会把到达的任务放到缓存队列当中；</p>
</li>
<li><p><code>maximumPoolSize</code>：线程池最大线程数，这个参数也是一个非常重要的参数，它表示在线程池中最多能创建多少个线程；
keepAliveTime：表示线程没有任务执行时最多保持多久时间会终止。默认情况下，只有当线程池中的线程数大于corePoolSize时，keepAliveTime才会起作用，直到线程池中的线程数不大于corePoolSize，即当线程池中的线程数大于corePoolSize时，如果一个线程空闲的时间达到keepAliveTime，则会终止，直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法，在线程池中的线程数不大于corePoolSize时，keepAliveTime参数也会起作用，直到线程池中的线程数为0；</p>
</li>
<li><code>unit</code>：参数keepAliveTime的时间单位，有7种取值，在TimeUnit类中有7种静态属性：</li>
<li><code>workQueue</code>：一个阻塞队列，用来存储等待执行的任务，这个参数的选择也很重要，会对线程池的运行过程产生重大影响，一般来说，这里的阻塞队列有以下几种选择：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ArrayBlockingQueue;//</span><br><span class="line">LinkedBlockingQueue;//链式结构的阻塞队列，作为Executors.newFixThreadPool()生成线程池的默认队列，入列出列快，但是同时会产生Node对象</span><br><span class="line">SynchronousQueue;//同步队列，没有存储能力，作为Executors.newCacheThreadPool()线程池的默认队列</span><br></pre></td></tr></table></figure>
<ul>
<li><code>threadFactory</code>：线程工厂，主要用来创建线程；</li>
<li><code>handler</code>：表示当拒绝处理任务时的策略，有以下四种饱和策略：</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor.AbortPolicy:<span class="comment">//丢弃任务并抛出RejectedExecutionException异常。</span></span><br><span class="line">ThreadPoolExecutor.DiscardPolicy：<span class="comment">//也是丢弃任务，但是不抛出异常。</span></span><br><span class="line">ThreadPoolExecutor.DiscardOldestPolicy：<span class="comment">//丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）</span></span><br><span class="line">ThreadPoolExecutor.CallerRunsPolicy：<span class="comment">//由调用线程处理该任务</span></span><br></pre></td></tr></table></figure>
<h3 id="2-2-线程池的整体流程"><a href="#2-2-线程池的整体流程" class="headerlink" title="2.2 线程池的整体流程"></a>2.2 线程池的整体流程</h3><p>了解完线程池的参数，下面这张线程架构图能够很好的帮助我们深入理解Java的线程池：</p>
<p><img src="/images/threadPoolFramworkNew.png" alt=""></p>
<p><strong>ExecuteService简单的理解可以认为是：</strong></p>
<p>1.通过消费者模式来解耦线程资源和任务。（消费者模式真的是非常有用的模式，java的框架中大量使用到（logback也有使用，一个线程作为消费者来写日志，多个生产者将日志放入队列），只要涉及到需要解耦的可能都会考虑这个设计模式）</p>
<p>2.使用池的技术来管理稀缺资源，包括管理生命周期，监控等等</p>
<p>下面，借用<a href="http://www.infoq.com/cn/articles/java-threadPool" target="_blank" rel="noopener">Qcon</a>一张流程图来说说线程池的处理流程：</p>
<p><img src="/images/threadPoolFlow.jpg" alt=""></p>
<p><strong>1.首先线程池判断基本线程池是否已满？没满，创建一个工作线程来执行任务。满了，则进入下个流程。</strong></p>
<p><strong>2.其次线程池判断工作队列是否已满？没满，则将新提交的任务存储在工作队列里。满了，则进入下个流程。</strong></p>
<p><strong>3.最后线程池判断整个线程池是否已满？没满，则创建一个新的工作线程来执行任务，满了，则交给饱和策略来处理这个任务。</strong></p>
<h3 id="2-3如何创建一个线程池"><a href="#2-3如何创建一个线程池" class="headerlink" title="2.3如何创建一个线程池"></a>2.3如何创建一个线程池</h3><p>我们可以通过构造函数初始化一个自己想要的线程池，但是一般不推荐这么做，除非Executors工厂方法构造的线程池不能满足我们的要求。
下面介绍一下Executos的api创建的线程池的特点：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Executors</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">   *创建一个固定大小的线程池，每当提交一个任务就创建一个线程，知道达到线程池的最大数量，这时线程规模不在变化</span></span><br><span class="line"><span class="comment">   （如果某个线程发生了未知Exception，那么线程池将补充一个线程）</span></span><br><span class="line"><span class="comment">   **/</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newFixedThreadPool</span><span class="params">(<span class="keyword">int</span> nThreads)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(nThreads, nThreads,</span><br><span class="line">                                      <span class="number">0L</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                                      <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    *创建一个可缓存的线程池，如果线程当前规模超过处理的需求，那么回收空闲线程（默认60s回收一次），</span></span><br><span class="line"><span class="comment">    当需求增加时，则可以添加新的线程，线程池的规模不存在任何限制</span></span><br><span class="line"><span class="comment">    **/</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newCachedThreadPool</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(<span class="number">0</span>, Integer.MAX_VALUE,</span><br><span class="line">                                      <span class="number">60L</span>, TimeUnit.SECONDS,</span><br><span class="line">                                      <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    *是一个单线程的Executors，如果这个线程意外结束，则会创建另一个线程替代，newSingleThreadExecutor能保证任</span></span><br><span class="line"><span class="comment">    务串行执行，例如（FIFO，LIFO，优先级）</span></span><br><span class="line"><span class="comment">    *Netty中的NioEventLoop就是一个单线程的Executors，保证业务逻辑串行无锁执行</span></span><br><span class="line"><span class="comment">    **/</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExecutorService <span class="title">newSingleThreadExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> FinalizableDelegatedExecutorService</span><br><span class="line">            (<span class="keyword">new</span> ThreadPoolExecutor(<span class="number">1</span>, <span class="number">1</span>,</span><br><span class="line">                                    <span class="number">0L</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">                                    <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    *创建定时执行的线程池，功能类似Timer，建议使用newSingleThreadScheduledExecutor来取代Timer（</span></span><br><span class="line"><span class="comment">    1.Timer异常处理糟糕；2.Timer只会创建一个线程，不能保证定时的精确性）</span></span><br><span class="line"><span class="comment">    **/</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ScheduledExecutorService <span class="title">newSingleThreadScheduledExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DelegatedScheduledExecutorService</span><br><span class="line">            (<span class="keyword">new</span> ScheduledThreadPoolExecutor(<span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-3对比newFixedThreadPool-amp-newCachedThreadPool"><a href="#2-3对比newFixedThreadPool-amp-newCachedThreadPool" class="headerlink" title="2.3对比newFixedThreadPool&amp;newCachedThreadPool"></a>2.3对比newFixedThreadPool&amp;newCachedThreadPool</h3><p>了解newFixedThreadPool&amp;newCachedThreadPool的区别有助于我们更好的理解和使用线程池，那么这两者到底有什么不同呢？</p>
<p>默认newCachedThreadPool会创建一个corePoolSize为0，maximumPoolSize为Integer.maxValue，队列为SynchronousQueue的线程池，默认60s回收一次空闲线程。这意味着newCachedThreadPool创建的线程池能够自动适应，有效的避免了由于任务依赖而造成的饥饿问题。线程编程实战书上推荐为默认的选择。
当然，newCachedThreadPool也会有缺点，当程序处理速度跟不上任务进入队列的速度时候会造成大量的线程，可能会耗完程序CPU。</p>
<p>这个时候newFixedThreadPool使我们另外一个选择，默认会创建一个corePoolSize为nThread，maximumPoolSize也为nThread，线程队列为LinkedBlockingQueue的线程池，<code>队列大小为Integer.maxValue，也就是说是一个无界队列</code>，这个很危险，当程序处理速度跟不上任务进入队列的速度时候会造成大量的线程，会有大量的对象积压在任务队列里面，直到耗完程序内存。
所以，如果我们的线程池有可能会面临高并发访问的场景，我们在创建的时候一定要小心，一定要用构造好合适的初始化值。</p>
<p>这里的合适的初始化值主要指，线程的corePoolSize，maximumPoolSize，workerQueue&amp;handler，这里的workerQueue和handler尤为重要，<code>最好不要使用无界队列。使用有界队列最坏的情况可能会造成部分任务无法响应，但至少能保证大部分的任务正常执行。而且我们还可以定制自己的handler（饱和策略）来处理这些处理不了的任务。</code></p>
<h3 id="2-4线程池的饱和策略"><a href="#2-4线程池的饱和策略" class="headerlink" title="2.4线程池的饱和策略"></a>2.4线程池的饱和策略</h3><p>当有界队列被填满了后，饱和策略开始发挥作用(<code>如果某个任务被提交到某一个已经被关闭的Executor时，也会用到饱和策略</code>)。ThreadPoolExecutor的饱和策略可以通过setRejectedExecutionHandler来修改。JDK提供几种不同的RejectedExecutionHandler实现，每种实现都包含不同的饱和策略：AbortPolicy，CallerRunsPolicy，DiscardPlolicy和DiscardOldestPolicy。
<strong>“中止（Abort）”策略是默认的饱和策略，该策略将抛出未检查的RejectExecutionException</strong>，调用者可以捕获这个异常，然后根据需求编写自己的处理代码。</p>
<p>当新提交的任务无法保存到该队列。“抛弃(Discard)”策略将会悄悄的抛弃该任务。</p>
<p>“抛弃最旧的（Discard-Oldest）”将会抛弃下一个将被执行的任务，然后尝试重新提交新的任务。<strong>如果工作队列是一个优先队列，那么“抛弃最旧” 的饱和策略则是抛弃优先级最高的任务，因此最好不要将“抛弃最旧的”饱和策略和优先队列一起使用</strong>。</p>
<p>“调用者运行（Caller-Runs）”实现了一种调节机制，该策略既不会抛弃任务，也不会抛出异常，而是将某些任务回退调用者，从而降低新任务流量。它不会在线程池的某个线程中执行新提交的任务，而是在一个调用了execute的线程中执行该任务。
我们可以将WebServer为例说明“调用者运行（Caller-Runs）”饱和策略。
当线程池中所有的线程都被占用，并且工作队列被填满后，下一个任务会调用executor时在主线程中执行。由于执行任务需要一定的时间，因此主线程至少在一段时间内不能提交任何任务，从而使得工作者线程有时间来处理正在执行的任务。在这期间主线程不会调用accept，因此到达的请求将被保存在TCP层的队列中而不是在应用程序的队列中。如果持续过载，那么TCP层将最终发现他的请求队列被填满，因此同样会开始抛弃请求。<strong>当服务器过载时，这种过载情况会逐渐想外蔓延开来–从线程池到工作队列到应用程序到TCP层队列，最终到达客户端，导致服务器在高负载下实现一种平缓的性能降低。</strong></p>
<p>调用者运行饱和策略示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ThreadPoolExecutor executor = <span class="keyword">new</span> ThreadPoolExecutor(N_THREADS, N_HREADS, <span class="number">0L</span>, TimeUnit.MILLISECONDS, <span class="keyword">new</span> LinkedBlockingQueue&lt;Runable&gt;(CAPCITY));</span><br><span class="line">executor.setRejectedExecutionHandler(<span class="keyword">new</span> ThreadPoolExecutor.CallerRansPolicy());</span><br></pre></td></tr></table></figure>
<h3 id="2-5线程池的workQueue"><a href="#2-5线程池的workQueue" class="headerlink" title="2.5线程池的workQueue"></a>2.5线程池的workQueue</h3><p>线程池基本的任务排队方法有三种：无界队列，有界队列，和同步移交。</p>
<p>无界队列&amp;有界队列对应的都是<code>LinkListBlockingQueue</code>，即是链式结构的阻塞队列，比较容易理解，暂不作详细探讨。</p>
<p>这里重点说明<code>SynchronousQueue</code>：基于BlockingQueue实现的，但实际上它不是一个真正的队列。因为他不会为队列中的元素维护存储空间，与其他的队列不同，它维护一组线程，这些线程在等待着把元素加入或者移除队列。这种队列的实现看似奇怪，但由于它可以直接交付工作，从而降低了数据从生产移动到消费者的延迟。直接交付的方式还可以将更多关于任务的状态反馈给生产者。</p>
<p><strong>注意，仅当有足够的消费者，并且总有一个消费者准备好获取交付的工作时，才适合使用同步队列。（只有当线程池是无界队列或者可以拒绝任务，同步队列才有使用价值）</strong>
[newCacheThreadPool线程数量没有上线，所以newCacheThreadPool工厂方法使用了SynchronousQueue，]</p>
<h3 id="2-6-线程池的关闭"><a href="#2-6-线程池的关闭" class="headerlink" title="2.6 线程池的关闭"></a>2.6 线程池的关闭</h3><p>线程池的关闭我们就要交给ExecutorService了，这也是为什么推荐使用Executors框架来替代线程（即便是单个的线程，也建议使用Executos框架）。</p>
<p>ExecutorService 提供了两个方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">*正常关闭</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">shutdown</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">*首先关闭当前正在执行的任务，然后返回未启动的任务清单</span></span><br><span class="line"><span class="comment">**/</span></span><br><span class="line"><span class="function">List&lt;Runnable&gt; <span class="title">shutdownNow</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>
<p>两种关闭的差异来自安全性和响应性。强行关闭响应快，风险大。一般，没特殊要求，建议使用shutdown();</p>
<p>虽然调用shutdown程序会在关闭前执行完所有启动的线程，但是有的时候我们希望队列中所有的task都不要漏掉，不妨加一个个Jvm hook：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Runtime.getRuntime().addShutdownHook(<span class="keyword">new</span> Thread()&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">     <span class="comment">//处理一些未完成的工作</span></span><br><span class="line">    &#125;<span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">     e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">   &#125;</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<h2 id="3-线程池的配置"><a href="#3-线程池的配置" class="headerlink" title="3. 线程池的配置"></a>3. 线程池的配置</h2><h3 id="3-1线程池大小"><a href="#3-1线程池大小" class="headerlink" title="3.1线程池大小"></a>3.1线程池大小</h3><p>一般说来，大家认为线程池的大小经验值应该这样设置：（其中N为CPU的个数）</p>
<p><strong>如果是CPU密集型应用，则线程池大小设置为N+1</strong></p>
<p><strong>如果是IO密集型应用，则线程池大小设置为2N+1</strong></p>
<p>如果一台服务器上只部署这一个应用并且只有这一个线程池，那么这种估算或许合理，具体还需自行测试验证。
但是，IO优化中，这样的估算公式可能更适合：
最佳线程数目 = （（线程等待时间+线程CPU时间）/线程CPU时间 ）* CPU数目
因为很显然，线程等待时间所占比例越高，需要越多线程。线程CPU时间所占比例越高，需要越少线程。</p>
<p>下面举个例子：
比如平均每个线程CPU运行时间为0.5s，而线程等待时间（非CPU运行时间，比如IO）为1.5s，CPU核心数为8，那么根据上面这个公式估算得到：<code>((0.5+1.5)/0.5)*8=32</code>。这个公式进一步转化为：
<strong>最佳线程数目 = （线程等待时间与线程CPU时间之比 + 1）* CPU数目</strong></p>
<p>这个只是估算值，实际通过测试调优得出合理值。</p>
<h3 id="3-2-合理的配置线程池"><a href="#3-2-合理的配置线程池" class="headerlink" title="3.2 合理的配置线程池"></a>3.2 合理的配置线程池</h3><p>要想合理的配置线程池，就必须首先分析任务特性，可以从以下几个角度来进行分析：</p>
<ul>
<li><strong>任务的性质</strong>：CPU密集型任务，IO密集型任务和混合型任务。</li>
<li><strong>任务的优先级</strong>：高，中和低。</li>
<li><strong>任务的执行时间</strong>：长，中和短。</li>
<li><strong>任务的依赖性</strong>：是否依赖其他系统资源，如数据库连接。</li>
</ul>
<p>任务性质不同的任务可以用不同规模的线程池分开处理。CPU密集型任务配置尽可能小的线程，如配置Ncpu+1个线程的线程池。IO密集型任务则由于线程并不是一直在执行任务，则配置尽可能多的线程，如2*Ncpu。混合型的任务，如果可以拆分，则将其拆分成一个CPU密集型任务和一个IO密集型任务，只要这两个任务执行的时间相差不是太大，那么分解后执行的吞吐率要高于串行执行的吞吐率，如果这两个任务执行时间相差太大，则没必要进行分解。我们可以通过Runtime.getRuntime().availableProcessors()方法获得当前设备的CPU个数。</p>
<p><code>优先级不同的任务可以使用优先级队列PriorityBlockingQueue来处理</code>。它可以让优先级高的任务先得到执行，需要注意的是如果一直有优先级高的任务提交到队列里，那么优先级低的任务可能永远不能执行。</p>
<p><code>执行时间不同的任务可以交给不同规模的线程池来处理，或者也可以使用优先级队列，让执行时间短的任务先执行</code>。</p>
<p>依赖数据库连接池的任务，因为线程提交SQL后需要等待数据库返回结果，如果等待的时间越长CPU空闲时间就越长，那么线程数应该设置越大，这样才能更好的利用CPU。</p>
<p>建议使用有界队列，有界队列能增加系统的稳定性和预警能力，可以根据需要设大一点，比如几千。有一次我们组使用的后台任务线程池的队列和线程池全满了，不断的抛出抛弃任务的异常，通过排查发现是数据库出现了问题，导致执行SQL变得非常缓慢，因为后台任务线程池里的任务全是需要向数据库查询和插入数据的，所以导致线程池里的工作线程全部阻塞住，任务积压在线程池里。如果当时我们设置成无界队列，线程池的队列就会越来越多，有可能会撑满内存，导致整个系统不可用，而不只是后台任务出现问题。当然我们的系统所有的任务是用的单独的服务器部署的，而我们使用不同规模的线程池跑不同类型的任务，但是出现这样问题时也会影响到其他任务。</p>
<h2 id="4-线程池的应用与扩展"><a href="#4-线程池的应用与扩展" class="headerlink" title="4.线程池的应用与扩展"></a>4.线程池的应用与扩展</h2><p>很多服务器都扩展的jdk自带的线程池来满足自己的需求，例如tomcat，motan…
通常，我们自己实现rpc服务器不可避免的用到线程池，参考借鉴他人的代码可以使我们少走很多弯路。</p>
<p>下面贴出motan中使用线程池的源代码供研究学习:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br></pre></td><td class="code"><pre><span class="line">	<span class="comment">/*</span></span><br><span class="line"><span class="comment">	 *  Copyright 2009-2016 Weibo, Inc.</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 *    Licensed under the Apache License, Version 2.0 (the "License");</span></span><br><span class="line"><span class="comment">	 *    you may not use this file except in compliance with the License.</span></span><br><span class="line"><span class="comment">	 *    You may obtain a copy of the License at</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 *        http://www.apache.org/licenses/LICENSE-2.0</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 *    Unless required by applicable law or agreed to in writing, software</span></span><br><span class="line"><span class="comment">	 *    distributed under the License is distributed on an "AS IS" BASIS,</span></span><br><span class="line"><span class="comment">	 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span></span><br><span class="line"><span class="comment">	 *    See the License for the specific language governing permissions and</span></span><br><span class="line"><span class="comment">	 *    limitations under the License.</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">package</span> com.weibo.api.motan.transport.netty;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.Executors;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.RejectedExecutionException;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.RejectedExecutionHandler;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.ThreadFactory;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.ThreadPoolExecutor;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.TimeUnit;</span><br><span class="line">	<span class="keyword">import</span> java.util.concurrent.atomic.AtomicInteger;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">import</span> org.jboss.netty.util.internal.LinkedTransferQueue;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * &lt;pre&gt;</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * 代码和思路主要来自于：</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * tomcat :</span></span><br><span class="line"><span class="comment">	 * 		org.apache.catalina.core.StandardThreadExecutor</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * java.util.concurrent</span></span><br><span class="line"><span class="comment">	 * threadPoolExecutor execute执行策略： 		优先offer到queue，queue满后再扩充线程到maxThread，如果已经到了maxThread就reject</span></span><br><span class="line"><span class="comment">	 * 						   		比较适合于CPU密集型应用（比如runnable内部执行的操作都在JVM内部，memory copy, or compute等等）</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * StandardThreadExecutor execute执行策略：	优先扩充线程到maxThread，再offer到queue，如果满了就reject</span></span><br><span class="line"><span class="comment">	 * 						      	比较适合于业务处理需要远程资源的场景</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * &lt;/pre&gt;</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@author</span> maijunsheng</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@version</span> 创建时间：2013-6-20</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StandardThreadExecutor</span> <span class="keyword">extends</span> <span class="title">ThreadPoolExecutor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_MIN_THREADS = <span class="number">20</span>;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_MAX_THREADS = <span class="number">200</span>;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> DEFAULT_MAX_IDLE_TIME = <span class="number">60</span> * <span class="number">1000</span>; <span class="comment">// 1 minutes</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">protected</span> AtomicInteger submittedTasksCount;	<span class="comment">// 正在处理的任务数</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> maxSubmittedTaskCount;				<span class="comment">// 最大允许同时处理的任务数</span></span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(DEFAULT_MIN_THREADS, DEFAULT_MAX_THREADS);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThread, <span class="keyword">int</span> maxThreads)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThread, maxThreads, maxThreads);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThread, <span class="keyword">int</span> maxThreads, <span class="keyword">long</span> keepAliveTime, TimeUnit unit)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThread, maxThreads, keepAliveTime, unit, maxThreads);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThreads, <span class="keyword">int</span> maxThreads, <span class="keyword">int</span> queueCapacity)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThreads, maxThreads, queueCapacity, Executors.defaultThreadFactory());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThreads, <span class="keyword">int</span> maxThreads, <span class="keyword">int</span> queueCapacity, ThreadFactory threadFactory)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThreads, maxThreads, DEFAULT_MAX_IDLE_TIME, TimeUnit.MILLISECONDS, queueCapacity, threadFactory);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThreads, <span class="keyword">int</span> maxThreads, <span class="keyword">long</span> keepAliveTime, TimeUnit unit, <span class="keyword">int</span> queueCapacity)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, Executors.defaultThreadFactory());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThreads, <span class="keyword">int</span> maxThreads, <span class="keyword">long</span> keepAliveTime, TimeUnit unit,</span></span></span><br><span class="line"><span class="function"><span class="params">			<span class="keyword">int</span> queueCapacity, ThreadFactory threadFactory)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>(coreThreads, maxThreads, keepAliveTime, unit, queueCapacity, threadFactory, <span class="keyword">new</span> AbortPolicy());</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">StandardThreadExecutor</span><span class="params">(<span class="keyword">int</span> coreThreads, <span class="keyword">int</span> maxThreads, <span class="keyword">long</span> keepAliveTime, TimeUnit unit,</span></span></span><br><span class="line"><span class="function"><span class="params">			<span class="keyword">int</span> queueCapacity, ThreadFactory threadFactory, RejectedExecutionHandler handler)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">super</span>(coreThreads, maxThreads, keepAliveTime, unit, <span class="keyword">new</span> ExecutorQueue(), threadFactory, handler);</span><br><span class="line">		((ExecutorQueue) getQueue()).setStandardThreadExecutor(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">		submittedTasksCount = <span class="keyword">new</span> AtomicInteger(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 最大并发任务限制： 队列buffer数 + 最大线程数</span></span><br><span class="line">		maxSubmittedTaskCount = queueCapacity + maxThreads;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">execute</span><span class="params">(Runnable command)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">int</span> count = submittedTasksCount.incrementAndGet();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// 超过最大的并发任务限制，进行 reject</span></span><br><span class="line">		<span class="comment">// 依赖的LinkedTransferQueue没有长度限制，因此这里进行控制</span></span><br><span class="line">		<span class="keyword">if</span> (count &gt; maxSubmittedTaskCount) &#123;</span><br><span class="line">			submittedTasksCount.decrementAndGet();</span><br><span class="line">			getRejectedExecutionHandler().rejectedExecution(command, <span class="keyword">this</span>);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="keyword">super</span>.execute(command);</span><br><span class="line">		&#125; <span class="keyword">catch</span> (RejectedExecutionException rx) &#123;</span><br><span class="line">			<span class="comment">// there could have been contention around the queue</span></span><br><span class="line">			<span class="keyword">if</span> (!((ExecutorQueue) getQueue()).force(command)) &#123;</span><br><span class="line">				submittedTasksCount.decrementAndGet();</span><br><span class="line"></span><br><span class="line">				getRejectedExecutionHandler().rejectedExecution(command, <span class="keyword">this</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getSubmittedTasksCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">this</span>.submittedTasksCount.get();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMaxSubmittedTaskCount</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> maxSubmittedTaskCount;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">afterExecute</span><span class="params">(Runnable r, Throwable t)</span> </span>&#123;</span><br><span class="line">		submittedTasksCount.decrementAndGet();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * LinkedTransferQueue 能保证更高性能，相比与LinkedBlockingQueue有明显提升</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;pre&gt;</span></span><br><span class="line"><span class="comment"> * 		1) 不过LinkedTransferQueue的缺点是没有队列长度控制，需要在外层协助控制</span></span><br><span class="line"><span class="comment"> * &lt;/pre&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> maijunsheng</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExecutorQueue</span> <span class="keyword">extends</span> <span class="title">LinkedTransferQueue</span>&lt;<span class="title">Runnable</span>&gt; </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = -<span class="number">265236426751004839L</span>;</span><br><span class="line">	StandardThreadExecutor threadPoolExecutor;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">ExecutorQueue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">super</span>();</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setStandardThreadExecutor</span><span class="params">(StandardThreadExecutor threadPoolExecutor)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">this</span>.threadPoolExecutor = threadPoolExecutor;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 注：代码来源于 tomcat</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">force</span><span class="params">(Runnable o)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">if</span> (threadPoolExecutor.isShutdown()) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> RejectedExecutionException(<span class="string">"Executor not running, can't force a command into the queue"</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// forces the item onto the queue, to be used if the task is rejected</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">super</span>.offer(o);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 注：tomcat的代码进行一些小变更</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">offer</span><span class="params">(Runnable o)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">int</span> poolSize = threadPoolExecutor.getPoolSize();</span><br><span class="line"></span><br><span class="line">		<span class="comment">// we are maxed out on threads, simply queue the object</span></span><br><span class="line">		<span class="keyword">if</span> (poolSize == threadPoolExecutor.getMaximumPoolSize()) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">super</span>.offer(o);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// we have idle threads, just add it to the queue</span></span><br><span class="line">		<span class="comment">// note that we don't use getActiveCount(), see BZ 49730</span></span><br><span class="line">		<span class="keyword">if</span> (threadPoolExecutor.getSubmittedTasksCount() &lt;= poolSize) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">super</span>.offer(o);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// if we have less threads than maximum force creation of a new</span></span><br><span class="line">		<span class="comment">// thread</span></span><br><span class="line">		<span class="keyword">if</span> (poolSize &lt; threadPoolExecutor.getMaximumPoolSize()) &#123;</span><br><span class="line">			<span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// if we reached here, we need to add it to the queue</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">super</span>.offer(o);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-一些问题"><a href="#5-一些问题" class="headerlink" title="5.一些问题"></a>5.一些问题</h2><h3 id="5-1什么时候线程池能够最有效的提升性能？"><a href="#5-1什么时候线程池能够最有效的提升性能？" class="headerlink" title="5.1什么时候线程池能够最有效的提升性能？"></a>5.1什么时候线程池能够最有效的提升性能？</h3><blockquote>
<p>当大量任务相互独立且同构时才能体现出程序的工作负载分配到多个任务带来的真正性能提升。所以如果任务队列里面的任务有相互依赖，或者存在不同的任务，我们需要谨慎的处理。
netty中的线程池就会同时处理IO任务和少量的定时任务，我们可以通过分配适当的执行比例ratio来优化。
当线程中的任务出现依赖的情况，我们尤其要适当的增大线程池的大小，以防止任务阻塞，造成的线程饥饿。</p>
</blockquote>
<h3 id="5-2-如何处理线程池中部分运行时间较长的任务？"><a href="#5-2-如何处理线程池中部分运行时间较长的任务？" class="headerlink" title="5.2 如何处理线程池中部分运行时间较长的任务？"></a>5.2 如何处理线程池中部分运行时间较长的任务？</h3><blockquote>
<p>如果线程池中出现运行时间较长的任务，即使不出现死锁，线程的响应速度也会变得非常糟糕。执行时间较长的任务不仅会造成线程池的阻塞，甚至还会增加执行时间较短的任务的服务时间。
有一项技术可以缓存执行时间较长的任务的影响，即限定任务等待资源的时间，而不要无限制的等待。如果等待时间超时，那么可以把任务标志为失败，然后终止任务或者将任务重新放入队列。
当然如果线程池中总是充满被阻塞的任务，那么也很有可能说明线程池的太小。</p>
</blockquote>
<h2 id="6-总结"><a href="#6-总结" class="headerlink" title="6.总结"></a>6.总结</h2><p>使用线程池的时候我们要合理设置参数以满足我们的期望，比如corePoolSize&amp;maxPoolSize&amp;blokingQueueSize，<code>JDK默认的线程池会先初始化corePoolSize的线程数，如果不够，则继续offer满blokingQueueSize，直到达到blokingQueueSize才会增加maxPoolSize</code>。如果我们把blokingQueueSize设置无限大，显然maxPoolSize就没有作用了。对于一些IO密集的任务，我们需要大量的线程提升效率的时候显然是不合理的。</p>
<p>饱和策略一定也不要忽视，合理的饱和策略处理异常情况才能使我们的程序更加稳定。</p>
<p>线程池的大小一定要分情况讨论，首先考虑CPU密集或者IO密集，其次考虑任务是否有依赖关系，有依赖关系的需要稍稍设置大些，以免造成线程饥饿死锁。是否有长时间任务等等。</p>
<p>生产消费者模式是个好模式，有着广泛的应用。</p>
<p><strong>最后，再强调一遍，尽量避免使用无界队列！！！</strong></p>
<h2 id="7-延伸阅读："><a href="#7-延伸阅读：" class="headerlink" title="7.延伸阅读："></a>7.延伸阅读：</h2><p><a href="http://calvin1978.blogcn.com/articles/tomcat-threadpool.html" target="_blank" rel="noopener">江南白衣-Tomcat线程池，更符合大家想象的可扩展线程池</a></p>
<p><a href="http://www.infoq.com/cn/articles/java-threadPool" target="_blank" rel="noopener">聊聊并发（三）——JAVA线程池的分析和使用</a></p>
<hr>
<p>写在后面：</p>
<p>[注]：未经许可，严禁转载[文章会随时更新补充…随时修改可能错误的观点]</p>
<p>写一遍文章真累…org</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016-09-16-IM-notes-discuss.html" rel="prev" title="IM开发日记-漫谈">
                IM开发日记-漫谈 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-概述"><span class="nav-number">1.</span> <span class="nav-text">1.概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-线程池的基础知识"><span class="nav-number">2.</span> <span class="nav-text">2.线程池的基础知识</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1线程池的构造方法"><span class="nav-number">2.1.</span> <span class="nav-text">2.1线程池的构造方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-线程池的整体流程"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 线程池的整体流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3如何创建一个线程池"><span class="nav-number">2.3.</span> <span class="nav-text">2.3如何创建一个线程池</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3对比newFixedThreadPool-amp-newCachedThreadPool"><span class="nav-number">2.4.</span> <span class="nav-text">2.3对比newFixedThreadPool&amp;newCachedThreadPool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4线程池的饱和策略"><span class="nav-number">2.5.</span> <span class="nav-text">2.4线程池的饱和策略</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-5线程池的workQueue"><span class="nav-number">2.6.</span> <span class="nav-text">2.5线程池的workQueue</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-6-线程池的关闭"><span class="nav-number">2.7.</span> <span class="nav-text">2.6 线程池的关闭</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-线程池的配置"><span class="nav-number">3.</span> <span class="nav-text">3. 线程池的配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1线程池大小"><span class="nav-number">3.1.</span> <span class="nav-text">3.1线程池大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-合理的配置线程池"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 合理的配置线程池</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-线程池的应用与扩展"><span class="nav-number">4.</span> <span class="nav-text">4.线程池的应用与扩展</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-一些问题"><span class="nav-number">5.</span> <span class="nav-text">5.一些问题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1什么时候线程池能够最有效的提升性能？"><span class="nav-number">5.1.</span> <span class="nav-text">5.1什么时候线程池能够最有效的提升性能？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-如何处理线程池中部分运行时间较长的任务？"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 如何处理线程池中部分运行时间较长的任务？</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-总结"><span class="nav-number">6.</span> <span class="nav-text">6.总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-延伸阅读："><span class="nav-number">7.</span> <span class="nav-text">7.延伸阅读：</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
